﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using FeedAgregator;
using System.Web.Caching;

/// <summary>
/// Summary description for DataAccessHelper
/// </summary>
public class DataAccessHelper
{

    public const string AllCategoriesKey = "AllCategoriesKey";
    public const string AllTagsKey = "AllTagsKey";
    public const string TotalNewsNumberKey = "TotalNewsNumberKey";
    public const string Last24NewsNumberKey = "Last24NewsNumberKey";
    public const string MostReadedKey = "MostReadedKey";
    public const string LastBusinessKey = "LastBusinessKey";
    public const string LastFinanceKey = "LastFinanceKey";
    public const string LastAutomotiveKey = "LastAutomotiveKey";
    public const string LastForMenKey = "LastForMenKey";
    public const string ItemsWithImagesKey = "ItemsWithImagesKey";

    public static List<FeedCategory> GetAllCategories()
    {
        List<FeedCategory> result;
        Cache cache = HttpRuntime.Cache;
        if (cache[AllCategoriesKey] == null)
        {
            using (FeedSignalDataContext ctx = new FeedSignalDataContext())
            {
                result = (from cats in ctx.FeedCategories
                          select cats).ToList();
            }
            cache.Add(AllCategoriesKey, result, null, DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = cache[AllCategoriesKey] as List<FeedCategory>;
        }
        return result;
    }

    public static String GetCategoryTitleById(int catId)
    {
        string result = (from cats in GetAllCategories()
                         where cats.ID == catId
                         select cats.CategoryName).Single();
        return result;
    }

    public static Feed GetFeedByID(int feedId)
    {
        Feed result = null;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            result = (from feeds in ctx.Feeds
                      where feeds.ID == feedId
                      select feeds).SingleOrDefault();

        }
        return result;
    }

    public static List<Tag> GetAllTags()
    {
        Cache cache = HttpRuntime.Cache;
        List<Tag> result;
        if (cache[AllTagsKey] == null)
        {
            result = GetAllTagsFromDatabase();
            cache.Add(AllTagsKey, result, null, DateTime.Now.AddMinutes(120), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = cache[AllTagsKey] as List<Tag>;
        }
        return result;
    }

    private static List<Tag> GetAllTagsFromDatabase()
    {
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            List<Tag> allTags = new List<Tag>();

            var tagsQuery = from tags in ctx.Tags
                            orderby tags.FeedItemTagRelations.Count() descending
                            select new { TagName = tags.TagName, Weight = tags.FeedItemTagRelations.Count() };
            foreach (var item in tagsQuery)
            {
                Tag tagToAdd = new Tag();
                tagToAdd.TagName = item.TagName;
                tagToAdd.Weight = item.Weight;
                allTags.Add(tagToAdd);
            }


            return allTags;
        }
    }



    public static FeedItem GetFeedItemByID(int feedItemID)
    {
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        where items.ID == feedItemID
                        select items;
            return query.SingleOrDefault();
        }
    }

    public static long GetTotalNewsNumber()
    {
        Cache cache = HttpRuntime.Cache;
        long result;
        if (cache[TotalNewsNumberKey] == null)
        {
            result = GetTotalNewsNumberFromDataBase();
            cache.Add(TotalNewsNumberKey, result, null, DateTime.Now.AddMinutes(120), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = (long)cache[TotalNewsNumberKey];
        }
        return result;
    }

    private static long GetTotalNewsNumberFromDataBase()
    {
        long result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        select items;

            result = query.Count();
        }
        return result;
    }



    public static long GetLast24NewsNumber()
    {
        Cache cache = HttpRuntime.Cache;
        long result;
        if (cache[Last24NewsNumberKey] == null)
        {
            result = GetLast24NewsNumberFromDataBase();
            cache.Add(Last24NewsNumberKey, result, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = (long)cache[Last24NewsNumberKey];
        }
        return result;
    }

    private static long GetLast24NewsNumberFromDataBase()
    {
        long result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        where items.PubDate > DateTime.Now.AddHours(-24)
                        select items;
            result = query.Count();
        }
        return result;
    }

    public static List<FeedItem> GetMostReaded()
    {
        Cache cache = HttpRuntime.Cache;
        List<FeedItem> result;
        if (cache[MostReadedKey] == null)
        {
            result = GetMostReadedFromDataBase();
            cache.Add(MostReadedKey, result, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = cache[MostReadedKey] as List<FeedItem>;
        }
        return result;
    }

    private static List<FeedItem> GetMostReadedFromDataBase()
    {
        List<FeedItem> result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems

                        select items;
            query = query.OrderByDescending(item => item.PubDate.Date).ThenByDescending(item => item.ReadHistories.Count());
            result = query.Take(7).ToList();
        }
        return result;

    }

  

  

  


    public static List<FeedItem> GetLastForMen()
    {
        Cache cache = HttpRuntime.Cache;
        List<FeedItem> result;
        if (cache[LastForMenKey] == null)
        {
            result = GetLastForMenFromDataBase();
            cache.Add(LastForMenKey, result, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = cache[LastForMenKey] as List<FeedItem>;
        }
        return result;
    }

    private static List<FeedItem> GetLastForMenFromDataBase()
    {
        List<FeedItem> result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        where items.Feed.CategoryID == CategoryIds.ForMen
                        orderby items.PubDate descending
                        select items;
            result = query.Take(7).ToList();
        }
        return result;

    }

   
   


    struct CategoryIds
    {
        public const int ForMen = 21;
        public const int Sport = 23;
    }

    public static List<FeedItem> GetItemsWithImages()
    {
        Cache cache = HttpRuntime.Cache;
        List<FeedItem> result;
        if (cache[ItemsWithImagesKey] == null)
        {
            result = GetItemsWithImagesFromDataBase();
            cache.Add(ItemsWithImagesKey, result, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }
        else
        {
            result = cache[ItemsWithImagesKey] as List<FeedItem>;
        }
        return result;
    }


    public static List<FeedItem> GetItemsWithImagesFromDataBase()
    {
        List<FeedItem> result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        where items.ItemContent.Contains(@"<img") &&
                        items.ItemContent.Contains(@"src=""http://")
                        && !items.ItemContent.Contains(@".gif")
                        orderby items.PubDate descending
                        select items;
            result = query.Take(7).ToList();
        }
        return result;
    }

    public static List<FeedItem> GetRelatedPosts(long FeedItemId)
    {
        List<FeedItem> result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        where items.ID > FeedItemId - 7
                        && items.ID < FeedItemId + 7 && items.ID != FeedItemId
                        orderby items.PubDate descending
                        select items;
            result = query.Take(7).ToList();
        }
        return result;
    }

    public static List<FeedItem> GetForFeed()
    {
        List<FeedItem> result;
        using (FeedSignalDataContext ctx = new FeedSignalDataContext())
        {
            var query = from items in ctx.FeedItems
                        orderby items.PubDate descending
                        select items;
            result = query.Take(15).ToList();
        }
        return result;
    }
}
